package com.onethinker.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
import com.onethinker.common.constants.OneThinkerConfigConstant;
import com.onethinker.common.constants.ProjectConstant;
import com.onethinker.common.utils.UploadFileUtils;
import com.onethinker.service.UploadPicService;
import com.qcloud.cos.exception.CosClientException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: yangyouqi
 * @Date: 2022/4/2 15:13
 * @Description:
 */
@Service
@Log4j2
class AlibabaCloudSavePicImpl implements UploadPicService {

    @Resource
    private OneThinkerConfigConstant oneThinkerConfigConstant;

    @Override
    public JSONObject uploadPic(HttpServletRequest request, String... uploadPath) {
        // 初始化阿里云 对象存储
        OSS ossClient = initAliyumOSS();
        // 上传文件名
        List<String> uploadPicNames = new ArrayList<>();
        try {
            // 获取multipartFile文件信息
//            MultipartFile multipartFile = UploadFileUtils.getMultipartFile(request);
            List<MultipartFile> multipartFiles = UploadFileUtils.getMultipartFiles(request);
            for (MultipartFile multipartFile : multipartFiles) {
                // 指定要上传到 COS 上对象键 (也是最终访问地址)
                String uploadPicName = UploadFileUtils.getUploadPicName(multipartFile.getOriginalFilename(), uploadPath,oneThinkerConfigConstant.picConfig.alibabaCloud.defaultPath);
                // 获取临时File文件并进行上传
                File localFile = UploadFileUtils.getPicTempFile(multipartFile);
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(oneThinkerConfigConstant.picConfig.alibabaCloud.bucketName, uploadPicName, localFile);
                 ObjectMetadata metadata = new ObjectMetadata();
                 metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
                 metadata.setObjectAcl(CannedAccessControlList.PublicRead);
                 // 设置不强制下载
                 metadata.setContentDisposition("inline");
                 putObjectRequest.setMetadata(metadata);
                // 上传文件
                ossClient.putObject(putObjectRequest);
                uploadPicNames.add(uploadPicName);
            }
        } catch (CosClientException | IOException e) {
            log.error("腾讯云文件上传异常：" + e.getCause());
        } finally {
            //关闭客户端(关闭后台线程)
            ossClient.shutdown();
        }
        // 返回相关上传文件信息
        return UploadFileUtils.getSavePicBaseInfo(uploadPicNames,oneThinkerConfigConstant.picConfig.alibabaCloud.host, ProjectConstant.PIC_SAVE_ALIYUM_OSS);
    }

    /**
     * 初始化并生成cos客户端
     * @return
     */
    private OSS initAliyumOSS() {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-"+ oneThinkerConfigConstant.picConfig.alibabaCloud.regionName +".aliyuncs.com";
        // 初始化用户身份信息（secretId, secretKey）。
        OSS ossClient = new OSSClientBuilder().build(endpoint, oneThinkerConfigConstant.picConfig.alibabaCloud.secretId, oneThinkerConfigConstant.picConfig.alibabaCloud.secretKey);
        return ossClient;
    }
}
